#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include "linux/i2c-dev.h"
#include "sys/ioctl.h"
#include "iic.h"
 
 
int iicfd;
 
//向IIC设备指定寄存器写入数据
void iic_write(unsigned char addr,unsigned char dat)
{
	unsigned char  buf[2];
	buf[0]=addr;
	buf[1]=dat;
	write(iicfd,&buf,2);
}
 
//读取IIC设备的指定寄存器
unsigned char iic_read(unsigned char addr)
{
	unsigned char buf=0;
	write(iicfd,&addr,1);
	read(iicfd,&buf,1);
	return buf;
}
//IIC设备挂载 注意在这里写入的是IIC设备的ID地址
void iic_init(void)
{
    iicfd = open(I2C_DEV, O_RDWR);
    if(iicfd < 0){
          printf("i2c2  device open failed \n");
    }
	else
	{
		printf("iic device open OK \n");
	}
}

int i2c_write(int fd, uint8_t addr, uint8_t reg, uint8_t data) {

    uint8_t buf[2];
    buf[0] = reg;
    buf[1] = data;
    if (write(fd, buf, 2) != 2) {
        return -1;
    }
    return 0;
	
}

int i2c_read(int fd, uint8_t addr, uint8_t reg, uint8_t *data, uint8_t len) {
    
	if (write(fd, &reg, 1) != 1) {
        return -1;
    }
    if (read(fd, data, len) != len) {
        return -1;
    }
    return 0;
}